package mhserver;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import mh.message.IncomingMessage;

/**
 * Netty's handler that processes the messages incoming from the clients.
 * 
 * @author Gianmarco Laggia
 * 
 */
public class MessageHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		//		System.out.println((String) msg);
		IncomingMessage m = (IncomingMessage) msg;
		ChannelFuture f = ctx.writeAndFlush(m.getCommand() + "\r\n");
		//				ctx.flush();
		f.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture cf) throws Exception {
				if (cf.isSuccess()) {
					System.out.println("Inviato");
				} else {
					System.out.println("non inviato");
					cf.cause().printStackTrace();
				}
			}
		});
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// Close the connection when an exception is raised.
		cause.printStackTrace();
		ctx.close();
	}
}
